//
//  MNDMessageViewController.m
//  minidai
//
//  Created by 谭伟 on 2017/5/2.
//  Copyright © 2017年 迷你金服. All rights reserved.
//

#import "MNDMessageViewController.h"
#import "MNDMessageModel.h"
#import "MNDAcountMessageModel.h"
#import "MNDAcountMsgTableViewCell.h"
#import "MNDWebViewController.h"
#import "SYRefreshControl.h"
#import "MNDLoginUserModel.h"
#import "MNDLoginViewController.h"
//cell重用标志符
#define MyMessageCell @"MyMessageCell"
#define SystemMessageCell @"SystemMessageCell"
#define kCheckMyMessageNotificationName @"CheckMyMessageNotificationName"
@interface MNDMessageViewController ()<UITableViewDataSource,UITableViewDelegate>
@property (nonatomic, strong) MJRefreshNormalHeader *refreshHeader;
@property (nonatomic, strong) MJRefreshAutoNormalFooter *refreshFooter;
@property (nonatomic, strong) MJRefreshNormalHeader *aountRefreshHeader;
@property (nonatomic, strong) MJRefreshAutoNormalFooter *acountRefreshFooter;
@property (weak, nonatomic) IBOutlet UITableView *messageTabView;
//系统消息
@property (weak, nonatomic) IBOutlet UIButton *systemMessageBtn;
//个人消息
@property (weak, nonatomic) IBOutlet UIButton *myMessageBtn;
/* 记录选择的按钮 */
@property (strong, nonatomic) UIButton *selectBtn;

/* <#Annotation#> */
@property (strong, nonatomic) NSMutableArray<MNDMessageModel*> *messageModelArr;
//@property (weak, nonatomic) IBOutlet UITableView *messageTableView;

@property (strong, nonatomic) NSMutableArray<MNDAcountMessageModel*> *acountMsgModelArr;


@property (weak, nonatomic) IBOutlet UITableView *acountMsgTabview;
//按钮底部线
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *btnBottomLineConstrait;

@property (strong, nonatomic)UIView *placeHolderMaskView;

@property (strong, nonatomic)UIView *placeAcountHolderMaskView;

//@property (weak, nonatomic) IBOutlet UIView *noDataView;

@end


NSInteger messagePageNumber = 0;
NSInteger acountMsgPageNumber = 1;

@implementation MNDMessageViewController

typedef NS_ENUM(NSUInteger,MessageType) {
    MessageTypeSystem = 101,//系统公告
    MessageTypeMy//我的消息
};


- (NSMutableArray<MNDAcountMessageModel *> *)acountMsgModelArr {
    if (!_acountMsgModelArr) {
        _acountMsgModelArr = [NSMutableArray array];
    }
    return _acountMsgModelArr;
}

- (NSMutableArray<MNDMessageModel *> *)messageModelArr {
    if (!_messageModelArr) {
        _messageModelArr = [NSMutableArray array];
    }
    return _messageModelArr;
}
- (void)viewDidLoad {
    [super viewDidLoad];
    self.acountMsgTabview.hidden = YES;
    self.messageTabView.hidden = NO;
    //默认进来为系统公告
    self.systemMessageBtn.selected = YES;
    self.selectBtn = self.systemMessageBtn;
    if (self.isShowAcountMsg == YES) {//从我的界面进入我的消息
        self.acountMsgTabview.hidden = NO;
        self.messageTabView.hidden = YES;
        self.btnBottomLineConstrait.constant = kScreenWidth*0.5;
        self.selectBtn.selected = NO;
        self.selectBtn = self.myMessageBtn;
        self.myMessageBtn.selected = YES;
    
    }
    //接收展示我的消息的通知
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(showMyMessage:) name:kCheckMyMessageNotificationName object:nil];
   
    [self setupUI];
//    [self loadData];
//    [self loadAcountMsgData];
    if(self.forumCode && self.forumCode.length > 0) {
        MNDWebViewController *webviewVC = [[MNDWebViewController alloc]init];
        webviewVC.hidesBottomBarWhenPushed = YES;
        webviewVC.naviBarHidden = YES;
        webviewVC.webViewUrl = [NSString stringWithFormat:@"%@%@%@",WebBaseURL,kMsgDetailBaseUrl,self.forumCode];
        
        [self.navigationController pushViewController:webviewVC animated:YES];
    }

    //设置无数据时的占位图
    [self creatMessageMaskView];
    [self creatAcountMessageMaskView];
    
    //            []; 一键设置消息已读
    [self readAllMessages: self.shouldReadAllMsg];
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
//    self.navigationController.navigationBar.hidden = NO;
    self.navigationController.navigationBar.tintColor = [UIColor orangeColor];
    self.navigationController.navigationBar.barTintColor = [UIColor whiteColor];
    
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark -加载数据
- (void)loadData:(BOOL)isPullDown {
    //判断上拉下拉
//    BOOL isPullDown = [self.refreshHeader isRefreshing];
    //默认5条
    NSInteger pagesize = 10;
    NSString *pagesizeStr;
    //如果下拉
    if (isPullDown) {//展示第一页数据
        if (self.messageModelArr.count <= 0 ) {
            [self.view beginLoading];
        }
        pagesizeStr = @"10";
        messagePageNumber = 1;
    } else {//上拉加载后面几页数据
        messagePageNumber++;
        NSInteger number = messagePageNumber*pagesize;
        pagesizeStr = [NSString stringWithFormat:@"%zd",number];
    }
    __weak typeof(self) weakSelf = self;

    //系统消息列表
    [APIManager sendRequestWithPath:API_NOTICE_LIST parameters:[MNDSign signedParamWithDict:@{@"pagesize": pagesizeStr}] method:kXMHTTPMethodGET onSuccess:^(ResponseModel *responseModel) {
        
        if (responseModel.status == ResponseSuccess) {
            [self.view endLoading];
            NSLog(@"data: %@", responseModel.data);
            NSArray *modelArr = [MNDMessageModel mj_objectArrayWithKeyValuesArray:responseModel.data];
            if (isPullDown) {
                [weakSelf.messageModelArr removeAllObjects];
            }
            weakSelf.messageModelArr = [[NSMutableArray alloc] init];
            for (MNDMessageModel *model in modelArr) {
                [weakSelf.messageModelArr addObject:model];
            }
            if (weakSelf.messageModelArr.count > 0) {
                weakSelf.placeHolderMaskView.hidden = YES;
            } else {
                weakSelf.placeHolderMaskView.hidden = NO;
            }
            [SYRefreshControl configAfterLoading:weakSelf.messageTabView hasData:self.messageModelArr.count];
        } else {
            [weakSelf.view endLoading];
            [NetworkProgressHUD showHudMsg:responseModel.msg[@"error"]];
            [SYRefreshControl configAfterLoading:weakSelf.messageTabView hasData:NO];
        }
        [weakSelf.messageTabView reloadData];
        
    } onFailure:^(NSError *error) {
        [weakSelf.view endLoading];
        [SYRefreshControl configAfterLoading:weakSelf.messageTabView hasData:YES];
        [NetworkProgressHUD showHudNetworkError:error];
    }];
}

- (void)loadAcountMsgData:(BOOL)isPullDown {
    
    if (![MNDLoginUserModel isUserLogin]) {
        return;
    }
    //默认5条
    NSInteger pagesize = 5;
    //如果下拉
    if (isPullDown) {//展示第一页数据
        if (self.acountMsgModelArr.count <= 0) {
            [self.view beginLoading];
        }
        acountMsgPageNumber = 1;
    } else {//上拉加载后面几页数据
        acountMsgPageNumber++;
    }
    __weak typeof(self) weakSelf = self;

    //个人消息
    [APIManager sendRequestWithPath:API_ACOUNT_MSG_LIST parameters:[MNDSign signedParamWithDict:@{@"pagesize": @(pagesize),@"perpage": @(acountMsgPageNumber)}] method:kXMHTTPMethodGET onSuccess:^(ResponseModel *responseModel) {
        
        if (responseModel.status == ResponseSuccess) {
            [weakSelf.view endLoading];
            NSArray *msgArr = [MNDAcountMessageModel mj_objectArrayWithKeyValuesArray:responseModel.data[@"msg_list"]];
            if ((isPullDown)) {
                [weakSelf.acountMsgModelArr removeAllObjects];
            }
            [weakSelf.acountMsgModelArr addObjectsFromArray:msgArr];
            
            if (weakSelf.acountMsgModelArr.count > 0) {
                weakSelf.placeAcountHolderMaskView.hidden = YES;
            } else {
                weakSelf.placeAcountHolderMaskView.hidden = NO;
            }
            NSLog(@"--------------------------%@",responseModel.data[@"msg_list"]);
            
            [SYRefreshControl configAfterLoading:self.acountMsgTabview hasData:msgArr.count];
            for (MNDAcountMessageModel *msgModel in msgArr) {
                if (msgModel.msgStatus.integerValue == -1) {
                    [weakSelf readAllMessages:YES];
                }
            }
        } else{
            [weakSelf.view endLoading];
            [SYRefreshControl configAfterLoading:self.acountMsgTabview hasData:NO];
            [NetworkProgressHUD showHudMsg:responseModel.msg[@"error"]];
        }
        [self.acountMsgTabview reloadData];
        [self.messageTabView reloadData];
        
    } onFailure:^(NSError *error) {
        [weakSelf.view endLoading];
        [SYRefreshControl configAfterLoading:weakSelf.acountMsgTabview hasData:NO];
//        [weakSelf.aountRefreshHeader endRefreshing];
//        [weakSelf.acountRefreshFooter endRefreshing];
        [NetworkProgressHUD showHudNetworkError:error];
    }];
}
#pragma mark -搭建界面
- (void)setupUI{
//    self.acountMsgTabview.estimatedRowHeight = 44;
//    self.acountMsgTabview.rowHeight = UITableViewAutomaticDimension;
    //系统消息
    self.messageTabView.rowHeight = UITableViewAutomaticDimension;
    self.messageTabView.estimatedRowHeight = 44;
    self.selectBtn = self.systemMessageBtn;
    
    WeakSelf(self);
    
    [SYRefreshControl configGifMJRefresh:self.messageTabView refreshType:MJRefreshSupportALl beginRefresh:NO timeLabelHidden:YES stateLabelHidden:YES refreshBlock:^{
        [weakself loadData:YES];
    } loadMoreBlock:^{
        [weakself loadData:NO];
    }];
    
    //我的消息
    self.acountMsgTabview.rowHeight = UITableViewAutomaticDimension;
    self.acountMsgTabview.estimatedRowHeight = 44;
    [SYRefreshControl configGifMJRefresh:self.acountMsgTabview refreshType:MJRefreshSupportALl beginRefresh:NO timeLabelHidden:YES stateLabelHidden:YES refreshBlock:^{
        [weakself loadAcountMsgData:YES];
    } loadMoreBlock:^{
        [weakself loadAcountMsgData:NO];
    }];
    
    [self loadData:YES];
    [self loadAcountMsgData:YES];
}

- (IBAction)clickMessageBtn:(UIButton *)sender {
 
    if (sender.tag == 101) {//系统消息
        self.acountMsgTabview.hidden = YES;
        self.messageTabView.hidden = NO;
        self.btnBottomLineConstrait.constant = 0;
        self.myMessageBtn.selected = NO;
        self.selectBtn.selected = NO;
        sender.selected = YES;
        self.selectBtn = sender;
    } else {//我的消息
        
        if (![MNDLoginUserModel isUserLogin]) {
            
            UIStoryboard *storyboard = [UIStoryboard storyboardWithName:@"Login" bundle:nil];
            MNDLoginViewController *loginVC = [storyboard instantiateViewControllerWithIdentifier:@"MNDLoginViewController"];
            UINavigationController *naviVC =[[UINavigationController alloc] initWithRootViewController:loginVC];
            loginVC.isCheckMyMessage = YES;
            [self presentViewController:naviVC animated:YES completion:^{
                
            }];
        }else {
            self.acountMsgTabview.hidden = NO;
            self.messageTabView.hidden = YES;
            self.btnBottomLineConstrait.constant = kScreenWidth*0.5;
            self.myMessageBtn.selected = NO;
            self.selectBtn.selected = NO;
            sender.selected = YES;
            self.selectBtn = sender;
        }
    }
    
    [self.acountMsgTabview reloadData];
    [self.messageTabView reloadData];
}

- (void)readAllMessages: (BOOL)read {
    
    if (!read) {
        return;
    }
    
    [APIManager sendRequestWithPath:API_MESSAGE_READ parameters:[MNDSign signedParam] method:kXMHTTPMethodPOST onSuccess:^(ResponseModel *responseModel) {
        
    } onFailure:^(NSError *error) {
        
    }];
}

- (void)showMyMessage:(NSNotification *)notification {
//    self.systemMessageBtn.selected = NO;
    self.acountMsgTabview.hidden = NO;
    self.messageTabView.hidden = YES;
    self.btnBottomLineConstrait.constant = kScreenWidth*0.5;
    self.selectBtn.selected = NO;
    self.myMessageBtn.selected = YES;
    self.selectBtn = self.myMessageBtn;
    acountMsgPageNumber = 0;
    [self loadAcountMsgData:YES];
}

#pragma mark - 无数据显示图片
- (void)creatMessageMaskView {
    UIView *maskView = [[UIView alloc]initWithFrame:self.view.bounds];
    maskView.backgroundColor = [UIColor colorWithRed:239/255.0 green:239/255.0 blue:244/255.0 alpha:1.0];
    //    [self.view insertSubview:maskView aboveSubview:self.tableView];
    [self.messageTabView addSubview:maskView];
    UIImageView *imgV = [[UIImageView alloc]initWithImage:[UIImage imageNamed:@"blankpage_emptydata"]];
    UILabel *tipLabel = [[UILabel alloc]init];
    tipLabel.text = @"哎呀~这里空空如也~";
    tipLabel.font = [UIFont systemFontOfSize:14];
    tipLabel.textColor = kColorGray;
    
    [maskView addSubview:tipLabel];
    [maskView addSubview:imgV];
    
    imgV.layer.cornerRadius = imgV.bounds.size.height*0.5;
    imgV.clipsToBounds = YES;
    [imgV mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.equalTo(maskView);
        make.centerY.equalTo(maskView).mas_offset(-80);
    }];
    [tipLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.equalTo(imgV);
        make.top.equalTo(imgV.mas_bottom).offset(10);
    }];
    
    self.placeHolderMaskView = maskView;
}

- (void)creatAcountMessageMaskView {
    UIView *maskView = [[UIView alloc]initWithFrame:self.view.bounds];
    maskView.backgroundColor = [UIColor colorWithRed:239/255.0 green:239/255.0 blue:244/255.0 alpha:1.0];
    //    [self.view insertSubview:maskView aboveSubview:self.tableView];
    [self.acountMsgTabview addSubview:maskView];
    UIImageView *imgV = [[UIImageView alloc]initWithImage:[UIImage imageNamed:@"blankpage_emptydata"]];
    UILabel *tipLabel = [[UILabel alloc]init];
    tipLabel.text = @"哎呀~这里空空如也~";
    tipLabel.font = [UIFont systemFontOfSize:14];
    tipLabel.textColor = kColorGray;
    
    [maskView addSubview:tipLabel];
    [maskView addSubview:imgV];
    
    imgV.layer.cornerRadius = imgV.bounds.size.height*0.5;
    imgV.clipsToBounds = YES;
    [imgV mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.equalTo(maskView);
        make.centerY.equalTo(maskView).mas_offset(-80);
    }];
    [tipLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.equalTo(imgV);
        make.top.equalTo(imgV.mas_bottom).offset(10);
    }];
    
    self.placeAcountHolderMaskView = maskView;
}


#pragma mark -UITableViewDataSource,UITableViewDelegate

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    if (tableView.tag == 300) {//系统公告
         return self.messageModelArr.count;
    }else {
        return self.acountMsgModelArr.count;
    }
    
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {

    if (tableView.tag == 300) {//系统公告
        UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:SystemMessageCell];
        UILabel *sysTitleLabel = [cell viewWithTag:201];
        sysTitleLabel.text = self.messageModelArr[indexPath.row].title;
        UILabel *sysTimeLabel = [cell viewWithTag:202];
        sysTimeLabel.text = self.messageModelArr[indexPath.row].forum_releasetime;
        UIImageView *imgV = [cell viewWithTag:203];
        imgV.image = [[UIImage imageNamed:@"dot_line"] resizableImageWithCapInsets:UIEdgeInsetsMake(1, 1, 1, 1)];
        return cell;
    }else {
        MNDAcountMsgTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:MyMessageCell];
        cell.aountMsgTimeLabel.text = self.acountMsgModelArr[indexPath.row].msgAddTime;
        cell.aountMsgTitleLabel.text = self.acountMsgModelArr[indexPath.row].msgTitle;
        cell.acountMsgContentLabel.text = self.acountMsgModelArr[indexPath.row].msgContent;
        return cell;
    }
}


- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    //公告
    if (tableView.tag == 300) {
        MNDWebViewController *mndWebViewController = [[MNDWebViewController alloc]init];

        MNDMessageModel *model = self.messageModelArr[indexPath.row];
        mndWebViewController.naviBarHidden = YES;
        mndWebViewController.hidesBottomBarWhenPushed = YES;
        //拼接URl
        mndWebViewController.webViewUrl = [NSString stringWithFormat:@"%@%@%@",WebBaseURL,kMsgDetailBaseUrl,model.forum_code];
        [self.navigationController pushViewController:mndWebViewController animated:YES];
    }
   
}

@end
